<template>
    <van-popup
        v-model:show="show"
        position="bottom"
        class="popup">
        <div class="van-picker__toolbar">
            <button
                type="button"
                @click="cancel"
                class="van-picker__cancel">{{ $st('wp-qu-xiao') }}</button>
            <div class="van-picker__title van-ellipsis"></div>
            <button
                type="button"
                class="van-picker__confirm"
                @click="confirm"
            >{{ $st('wp-que-ren') }}</button>
        </div>
        <div class="content">
            <baidu-map-location
                class="map"
                width="100%"
                height="300px"
                ref="baidumap"
                :address="selectAddress"
                :username="username"
                @changedPosition="onChangedPosition"
            />
            <div class="cells">
                <van-cell
                    center
                    title=""
                    is-link
                    clickable
                    @click="onClickShowAddress"
                    :value="selectAddress.title"
                >
                    <template #title>
                        <span class="red">*</span>
                        <span class="customer">{{$st('wp_Address')}}</span>
                    </template>
                    <template #label>
                        <van-icon name="location-o" />{{$st('wp_Click_to_locate')}}
                    </template>
                </van-cell>
            </div>
        </div>
    </van-popup>
    <van-action-sheet
        :title="$st('wp_Nearby_Address')"
        :close-on-click-action="true"
        style="height: 100%"
        v-model:show="showAddresses"
    >
        <van-cell
            clickable
            @click="onSelectAddress(item)"
            v-for="(item, index) in addresses"
            :title="item.title"
            :label="item.address"
            :key="index"
        />
    </van-action-sheet>
</template>
<script>
import { Toast } from 'vant';
import wx from 'weixin-js-sdk';
import Cookies from 'js-cookie';
import { selfI18n } from '@/i18n';
import { jssdksignature } from '@/api/server';
import { apiService } from '@/api/apiService';
import { computed, toRefs, reactive, watch, toRef } from 'vue';
import BaiduMapLocation from '@/components/clockin/BaiduMapLocation.vue';
import { showError } from '@/util/MessageDeal';

export default {
    components: { BaiduMapLocation },
    props: {
        popupShow: Boolean,
        point: Object
    },
    emits: ['cancel', 'confirm'],
    setup (props, ctx) {
        const username = Cookies.get('username');
        const point = toRef(props, 'point');
        const show = computed(() => {
            return props.popupShow;
        });

        const state = reactive({
            addresses: [],
            showAddresses: false,
            selectAddress: {
                title: '',
                address: '',
                point: { lng: 0.0, lat: 0.0 }
            }
        });

        const onClickShowAddress = () => {
            state.showAddresses = true;
        };

        // 获取微信定位授权
        const getWxPosition = (success) => {
            const param = {};
            if (window.__wxjs_is_wkwebview) {
                param.isios = true;
            }
            apiService({
                api: jssdksignature,
                param: param,
                success: (data) => {
                    wx.config({
                        debug: false,
                        appId: data.values.appId,
                        timestamp: data.values.timestamp,
                        nonceStr: data.values.nonceStr,
                        signature: data.values.signature,
                        jsApiList: ['getLocation', 'openLocation']
                    });
                    success && success();
                }
            });
        };

        const getLocAddress = () => {
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: (res) => {
                    const latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    const longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    // const speed = res.speed; // 速度，以米/每秒计
                    // const accuracy = res.accuracy; // 位置精度
                    // console.log(latitude, longitude)
                    // 转换为百度坐标轴然后获取地址
                    convertToBDPoint({
                        lat: latitude,
                        lng: longitude
                    });
                    // console.log(latitude + ',' + longitude);
                },
                fail: (err) => {
                    console.log(err);
                }
            });
        };

        /** 根据坐标点获取地址 */
        const getAddresses = (point) => {
            const mapGeo = new BMap.Geocoder();
            mapGeo.getLocation(
                point,
                (result) => {
                    if (result) {
                        let addresses = [];
                        if (result.surroundingPois.length >= 0) {
                            addresses = result.surroundingPois;
                        } else {
                            addresses = [result];
                        }
                        //  console.log(JSON.stringify(result));
                        state.selectAddress = {
                            title: result.address,
                            address: result.address,
                            point: result.point
                        };
                        state.addresses = [];
                        state.addresses.push(...addresses);
                    }
                },
                {
                    // 半径
                    poiRadius: 1000,
                    // 返回数目
                    numPois: 100
                }
            );
        };

        // 转换地址
        const convertToBDPoint = (point) => {
            const bdPoint = new BMap.Point(point.lng, point.lat);
            const bdConvert = new BMap.Convertor();
            const bdPoint_array = [bdPoint];
            bdConvert.translate(bdPoint_array, 1, 5, (data) => {
                if (data.status === 0) {
                    getAddresses(data.points[0]);
                }
            });
        };

        const onChangedPosition = (result) => {
            state.selectAddress = {
                title: result.title,
                address: result.address,
                point: result.point
            };
            state.addresses = [];
            state.addresses.push(...result.surroundingPois);
        };

        const InitWxPosition = () => {
            getWxPosition(() => {
                wx.ready(() => {
                    wx.checkJsApi({
                        jsApiList: [
                            'getLocation'
                        ],
                        success: function (res) {
                            if (res.checkResult.getLocation === false) {
                                Toast(selfI18n('wp_WeChat_edition_too_low'));
                            } else {
                                getLocAddress();
                            }
                        },
                        error: function (res) {
                            console.log(res);
                        }
                    });
                    wx.error(() => {
                        (selfI18n('wp_Failed_to_obtain_the_address_information_permission'));
                    });
                });
            });
        };

        // 取消
        const cancel = () => {
            ctx.emit('cancel');
        };

        // 确认
        const confirm = () => {
            if (!state.selectAddress.address || !state.selectAddress.point) {
                showError(selfI18n('wp-qing-dian-ji-jin-hang-ding-wei'));
                return;
            }
            ctx.emit('confirm', state.selectAddress);
        };

        // 选择一个地址
        const onSelectAddress = (item) => {
            state.selectAddress = item;
            state.showAddresses = false;
        };

        watch([show, point], (newValue, oldValue) => {
            if (newValue[0] && !newValue[1]) {
                InitWxPosition();
            } else if (newValue[0] && newValue[1]) {
                const bdPoint = new BMap.Point(newValue[1].lng, newValue[1].lat);
                getAddresses(bdPoint);
            }
        }, { immediate: true }, { deep: true });

        return {
            ...toRefs(state),
            show,
            username,
            cancel,
            confirm,
            onChangedPosition,
            onClickShowAddress,
            onSelectAddress
        };
    }
};
</script>
<style lang="scss" scoped>
.content {
    height: 379px;
    border-radius: 12px;
    margin: 15px;
    box-shadow: 0px 0px 5px 0px rgb(0 0 0 / 20%);
    background: #fff;
    position: relative;
    overflow: hidden;
    .cells {
        border-top: 1px solid var(--van-cell-border-color);
    }
}
</style>
